<template>
  <div>
    <video class="video-player" preload="auto" autoplay="autoplay" muted="muted" loop="loop">
      <source v-if="windowWidth>2000" src="resource/3840.ogg" type="video/ogg" />
      <source src="resource/1080.ogg" type="video/ogg" />
    </video>
    <div v-show="showLoginForm" class="login-container">
      <div id="loginForm">
        <!-- 平台模式 -->
        <template v-if="!isAIO">
          <div class="logo">
            <el-image :src="logoSrc" fit="cover">
              <div slot="error" class="image-slot">
                <img alt="LOGO" :src="logoSrcErr" fit="cover" width="100%" height="100%" />
              </div>
            </el-image>
          </div>
          <div class="logo-title">
            <el-image :src="logoTitleSrc" fit="cover">
              <div slot="error" class="image-slot">
                <img alt="标题" :src="logoTitleSrcErr" fit="cover" width="100%" height="100%" />
              </div>
            </el-image>
          </div>
        </template>
        <!-- 一体机模式 -->
        <template v-else>
          <div class="logo">
            <el-image v-if="logoSrc" :src="logoSrc" fit="cover">
              <div slot="error" class="image-slot">
                <img alt="LOGO" :src="logoSrcErr" fit="cover" width="100%" height="100%" />
              </div>
            </el-image>
          </div>
          <div class="logo-title">
            <div class="logo-title-text">{{logoTitle}}</div>
          </div>
        </template>
        <el-form class="login-form clearfix" ref="loginForm" :model="loginForm" :rules="loginRules" label-position="left" @submit.native.prevent>
          <el-form-item prop="accountName">
            <span class="svg-container">
              <i icon-class="user" />
            </span>
            <el-input
              ref="accountName"
              :disabled="loadingFlag"
              maxlength="30"
              autofocus="true"
              tabindex="1"
              v-model="loginForm.accountName"
              name="username"
              type="text"
              auto-complete="off"
              placeholder="请输入用户名"
              @keyup.enter.native="handleLogin"
              clearable
            >
              <i slot="prefix" class="el-input__icon iconfont icon_tubiao211" />
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <span class="svg-container">
              <i icon-class="password" />
            </span>
            <el-input
              ref="password"
              :disabled="loadingFlag"
              maxlength="30"
              tabindex="2"
              :type="pwdType"
              v-model="loginForm.password"
              name="password"
              auto-complete="off"
              placeholder="请输入密码"
              @keyup.enter.native="handleLogin"
              show-password
            >
              <i slot="prefix" class="el-input__icon iconfont icon_mimasuo" style="font-size:35px;" />
            </el-input>
          </el-form-item>
          <el-form-item prop="remembered">
            <el-checkbox @keyup.enter.native="remembered=!remembered" size="medium" tabindex="3" v-model="remembered" label="记住密码"></el-checkbox>
          </el-form-item>
          <el-form-item>
            <el-button
              tabindex="4"
              element-loading-text="载入中..."
              :loading="loadingFlag"
              type="primary"
              style="width:100%;"
              @click.native.prevent="handleLogin"
            >{{btnMsg}}</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="loding-container" v-if="loadingFlag">
      <img v-if="windowWidth>2000" src="../../assets/images/loading/loading3840.gif" fit="cover" />
      <img v-else src="../../assets/images/loading/loading1920.gif" fit="cover" />
    </div>
  </div>
</template>

<script>
import Qs from 'qs'
import Cookies from 'js-cookie'
import { findOrgByOrgCode } from '@/api/api'
import { mapActions, mapState } from 'vuex'
import { isvalidUsername } from '@/utils/validate'
import platConfig from '@/utils/platConfig'

export default {
  name: 'Login',
  data() {
    const validatePass = (rule, value, callback) => {
      if (value.length < 5) {
        callback(new Error('密码不能小于5位'))
      } else {
        callback()
      }
    }
    return {
      pwdType: 'password',
      loginForm: {
        accountName: '',
        password: '',
      },
      remembered: false, // 记住密码
      loginRules: {
        accountName: [
          {
            required: true,
            validator: (rule, value, callback) => {
              isvalidUsername(value)
                ? callback()
                : callback(new Error(rule.message))
            },
            message: '请输入正确的用户名',
            trigger: ['blur'],
          },
        ],
        password: [
          { required: true, validator: validatePass, trigger: ['blur'] },
        ],
      },
      platformCode: PLATCOEDEFAULT,
      logoSrc: '',
      logoTitleSrc: '',
      logoSrcErr: '',
      logoTitleSrcErr: '',
      logoTitle: '',
      btnMsg: '登录',
      loadingFlag: false,
      taskLoadingPoint: null, // 载入中... 点的定时任务
      taskLoadingPointNum: '', // 载入中... 点的定时任务计数器
      windowWidth: window.document.body.clientWidth,
      address: '', // 当前用户坐标信息
      showLoginForm: false,
      isAIO: ZHXF_IS_AIO,
    }
  },
  computed: {
    ...mapState(['userinfo', 'isLogin', 'platConfigInfo']),
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true,
    },
    platConfigInfo(val) {
      this.setPlatInfo(val)
    },
  },
  created: function () {
    this.showLoginForm = !this.$route.query.account
    let that = this
    if (Cookies.get('rmbUser') === 'remembered') {
      that.remembered = true
      that.loginForm.accountName = Cookies.get('userName')
      that.loginForm.password = Cookies.get('passWord')
    }
    that.getIpPosition() // 获取当前ip位置
    that.$Ctl.banF5andSelected()
    that.$Ctl.loading(0)
    that.$Cs.entryPageType(0) // 告诉C端，打开登录界面
    that.platformCode = that.GLOBAL.getPlatFormCodeByUrl()
    localStorage.setItem('ilinkBs_platformCode', that.platformCode || '')
    // 获取分平台key
    findOrgByOrgCode({ orgCode: that.platformCode }).then((re) => {
      localStorage.setItem('ilinkBs_platformId', re.data || '')
    })

    localStorage.setItem('ilinkBs_windowWidth', that.windowWidth)
    window.addEventListener('hashchange', function () {
      window.location.hash.indexOf('/login') > -1 && window.location.reload()
    })
    if (this.isAIO) {
      this.setPlatInfo(this.platConfigInfo)
    } else {
      this.getLogoSrc()
    }
  },
  mounted() {
    let account = this.$route.query.account
    if (account) {
      let _platCode = localStorage.getItem('ilinkBs_platformCode')
      $.getJSON(
        REMOTESTATICPATH + _platCode + '/bs-6.0/config.json',
        (data) => {
          if (data.autoLoginUsers && data.autoLoginUsers[account]) {
            this.loginForm.accountName = account
            this.loginForm.password = data.autoLoginUsers[account].password
            this.autoLogin()
          }
        }
      )
    }
  },
  methods: {
    ...mapActions(['requestLogin']),
    setPlatInfo(val) {
      let data = Object.assign({}, platConfig, val || {})
      this.logoSrc = data.logoPath
      this.logoTitle = data.simpleName
    },
    getLogoSrc() {
      let that = this
      that.logoSrc = REMOTESTATICPATH + that.platformCode + '/bs-6.0/logo.png'
      that.logoSrcErr = REMOTESTATICPATH + PLATCOEDEFAULT + '/bs-6.0/logo.png'
      that.logoTitleSrc =
        REMOTESTATICPATH + that.platformCode + '/bs-6.0/logoTitle.png'
      that.logoTitleSrcErr =
        REMOTESTATICPATH + PLATCOEDEFAULT + '/bs-6.0/logoTitle.png'
    },
    handleLogin() {
      let that = this
      that.$refs.loginForm.validate((valid) => {
        if (valid) {
          that.loadingFlag = true
          that.loadPointTask()
          let loginParams = {
            accountName: that.loginForm.accountName,
            password: this.$md5(that.loginForm.password),
            platformCode: that.platformCode,
            isEncrypt: true,
          }
          that.requestLogin(Qs.stringify(loginParams)).then((res) => {
            if (that.isLogin) {
              that.$Ctl.changePageSize(2)
              if (that.$Ctl.isCs()) {
                that.$Cs.loadingControl(1)
              }
              // 如果勾选了记住密码，启用cookie
              if (that.remembered) {
                Cookies.set('rmbUser', 'remembered', { expires: 30 })
                Cookies.set('userName', that.loginForm.accountName, {
                  expires: 30,
                })
                Cookies.set('passWord', that.loginForm.password, {
                  expires: 30,
                })
              } else {
                Cookies.remove('rmbUser')
                Cookies.set('userName', that.loginForm.accountName, {
                  expires: 30,
                })
                Cookies.remove('passWord')
              }

              // 登录成功设置下缓存
              localStorage.setItem(
                'ilinkBs_orgIds',
                that.$store.state.userInfo.organizationIds
              )
              localStorage.setItem(
                'ilinkBs_mapLocation',
                that.$store.state.userInfo.org.mapLocation ||
                  JSON.stringify(that.address)
              )
              that.$Ctl.initRouteList() // 初始化路由历史
              this.$store.commit('setShowCorrectPic', true)
              that.$router.push({ path: 'home' })
            } else {
              clearInterval(that.taskLoadingPoint)
              that.loadingFlag = false
              that.btnMsg = '登录'
              that.$Ctl.message(res.info, 'error')
            }
          })
        } else {
          return false
        }
      })
    },
    autoLogin() {
      let that = this
      that.loadingFlag = true
      that.loadPointTask()
      let loginParams = {
        accountName: that.loginForm.accountName,
        password: this.$md5(that.loginForm.password),
        platformCode: that.platformCode,
        isEncrypt: true,
      }
      that.requestLogin(Qs.stringify(loginParams)).then((res) => {
        if (that.isLogin) {
          this.$store.commit('setAutoLogin', true)
          that.$Ctl.changePageSize(2)
          // 登录成功设置下缓存
          localStorage.setItem(
            'ilinkBs_orgIds',
            that.$store.state.userInfo.organizationIds
          )
          localStorage.setItem(
            'ilinkBs_mapLocation',
            that.$store.state.userInfo.org.mapLocation ||
              JSON.stringify(that.address)
          )
          that.$Ctl.initRouteList() // 初始化路由历史
          that.$router.push({ path: 'home' })
        } else {
          clearInterval(that.taskLoadingPoint)
          that.loadingFlag = false
          that.btnMsg = '登录'
          that.$Ctl.message(res.info, 'error')
        }
      })
    },
    loadPointTask() {
      let that = this
      that.taskLoadingPoint = setInterval(() => {
        that.btnMsg = '载入中'
        let ponitStr = ''
        for (let i = 0; i < that.taskLoadingPointNum % 4; i++) {
          ponitStr += '.'
        }
        that.btnMsg += ponitStr
        that.taskLoadingPointNum++
      }, 400)
    },
    getIpPosition() {
      let that = this
      $.ajax({
        url: '//api.map.baidu.com/location/ip?ak=dyigaKsSXxx1fWV1pPOGBYSBZiYmosGX&coor=bd09ll',
        dataType: 'jsonp',
        success: function (data) {
          if (data.status === 0) {
            that.address = {
              lon: data.content.point.x,
              lat: data.content.point.y,
              zoom: 16,
            }
          } else {
            console.error('根据ip获取位置失败')
          }
        },
        error: function () {
          console.error('根据ip获取位置失败')
        },
      })
    },
  },
}
</script>
<style lang="scss">
.login-form {
  input {
    height: 68px;
    border: 1px solid rgba(119, 170, 246, 0.8);
    border-radius: 8px;
    background-color: transparent;
    font-size: 20px;
    letter-spacing: 1px;
    text-indent: 40px;
    color: #fff;
  }
  .el-input.is-disabled .el-input__inner {
    background-color: transparent;
    border: 1px solid rgba(119, 170, 246, 1);
  }
  button {
    font-size: 28px;
    line-height: 44px;
    letter-spacing: 10px;
    border-radius: 8px;
    background: linear-gradient(
      102deg,
      rgba(70, 153, 255, 1),
      rgba(59, 120, 245, 1)
    );
    border: none;
    .el-icon-loading {
      display: none;
    }
  }
  .iconfont {
    font-weight: bold;
    color: #008fff;
    font-size: 30px;
    line-height: 68px;
    padding-left: 15px;
  }
  input::-webkit-input-placeholder {
    color: #505961;
  }
  input::-moz-placeholder {
    /* Mozilla Firefox 19+ */
    color: #505961;
  }
  input:-moz-placeholder {
    /* Mozilla Firefox 4 to 18 */
    color: #505961;
  }
  input:-ms-input-placeholder {
    /* Internet Explorer 10-11 */
    color: #505961;
  }
  .el-checkbox__inner {
    zoom: 1.5;
    background-color: transparent;
  }
  .el-checkbox__label {
    color: #fff;
    font-size: 16px;
    font-weight: 300;
    color: #fff;
    letter-spacing: 1px;
  }
}
</style>
<style lang="scss" scoped>
.loign-input input {
  border: 1px solid rgba(119, 170, 246, 0.8);
  border-radius: 8px;
  background-color: transparent;
}
.video-player {
  background-color: transparent;
  display: block;
  position: absolute;
  z-index: 1;
  top: 0;
  width: auto;
  height: auto;
  left: 0px;
}
.login-container {
  position: relative;
  margin: 5% auto;
  height: 705px;
  width: 965px;
  background-image: url('../../assets/images/login/bgform3840.png');
  z-index: 99;
  .logo {
    position: absolute;
    left: calc(50% - 65px);
    top: 24px;
    height: 130px;
    width: 130px;
    .el-image {
      height: 100%;
      width: 100%;
      border-radius: 65px;
    }
  }
  .logo-title {
    position: absolute;
    left: 0;
    top: 180px;
    width: 100%;
    text-align: center;
    &-text {
      font-size: 50px;
      color: #2daeff;
    }
  }
  .login-form {
    position: absolute;
    top: 280px;
    width: 100%;
    padding: 0 24%;
  }
  .video-player {
    display: block;
    position: absolute;
    z-index: 1;
    top: 0;
    width: 100%;
    height: 100%;
    left: 0px;
    background-color: transparent;
  }
}
.loding-container {
  z-index: 100;
  position: fixed;
  bottom: 0;
  max-width: 100%;
  img {
    width: 100%;
  }
}
@media screen {
  .login-container {
    zoom: 0.8;
    margin: 8% auto;
  }
}
@media screen and (min-width: 1930px) {
}
@media screen and (min-width: 2565px) {
}
</style>
